import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入 登录子组件
import Login from '../components/Login.vue'   //登录组件
// 导入主页子组件
import Home from '../components/Home.vue'     //首页
import Welcome from '../components/Welcome.vue' //欢迎
import Users from '../components/user/Users.vue' //用户
import Rights from '../components/power/Rights.vue'//权限
import Roles from '../components/power/Roles.vue'//角色
import Cate from '../components/goods/Cate.vue'//商品分类
import Params from '../components/goods/Params.vue'//商品分类参数
import Goods from '../components/goods/List.vue'//商品列表
import GoodsAdd from '../components/goods/Add.vue'//添加商品
import OrderList from '../components/order/List.vue'//添加订单列表组件
import Report from '../components/report/Report.vue'//添加订单列表组件

Vue.use(VueRouter)

// 创建路由规则数组
const routes = [
  // 将 根路径 重定向到 登录url
  { path: '/', redirect: '/login' },
  // 注册 登录子组件 路由规则
  { path: '/login', component: Login },
  // 主页 子组件 路由规则
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Cate },
      { path: '/params', component: Params },
      { path: '/goods', component: Goods },
      { path: '/goods/add', component: GoodsAdd },
      { path: '/orders', component: OrderList },
      { path: '/reports', component: Report },
    ]
  }
]

// 创建 路由管理器 对象， 并传入 路由规则数组
const router = new VueRouter({
  routes
})

// 注册路由守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

// 导出路由管理器
export default router
